package com.leet.code.lcof;

public class Code29 {

    public static void main(String[] args) {

        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12}
        };
        for (int i : new Code29().spiralOrder(matrix)) {
            System.out.print(i + ",");
        }
        System.out.print("\b");


    }

    public int[] spiralOrder(int[][] matrix) {

        int m = matrix.length;
        if (m == 0) {
            return new int[0];
        }
        int n = matrix[0].length;
        if (n == 0) {
            return new int[0];
        }
        int l = m * n;
        int[] is = new int[l];
        int s = 0;
        int mStart = 0, mEnd = m - 1;
        int nStart = 0, nEnd = n - 1;


        while (s < l) {
            for (int ns = nStart; ns < nEnd && s < l; ns++) {
                is[s] = matrix[mStart][ns];
                s++;
            }

            for (int ms = mStart ; ms < mEnd && s < l; ms++) {
                is[s] = matrix[ms][nEnd];
                s++;
            }

            for (int ns = nEnd ; ns > nStart && s < l; ns--) {
                is[s] = matrix[mEnd][ns];
                s++;
            }

            for (int ms = mEnd ; ms > mStart && s < l; ms--) {
                is[s] = matrix[ms][nStart];
                s++;
            }

            if (mEnd > mStart) {
                mStart++;
                mEnd--;
            }
            if (nEnd > nStart) {
                nStart++;
                nEnd--;
            }


        }


        return is;
    }

}
